package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    public static final String WECHAT_URL="https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;

    /**
     * 微信登录
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        // 获取微信小程序的用户id
        String openId = getOpenId(userLoginDTO);
        if(StringUtils.isBlank(openId)){
            // 抛异常，因为没有拿到openId
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        // 根据微信返回的openId，判断当前用户是否是新用户
        // 调用mapper查询数据库获取用户
        User user = this.userMapper.getUserByOpenId(openId);
        // 没有在数据库中 用openId查询到数据，新用户
        if(user == null){
            user = new User();
            user.setOpenid(openId);
            user.setCreateTime(LocalDateTime.now());
            // 往用户表中新增一条数据，代表注册用户
            this.userMapper.insert(user);
        }
        // 如果查询到了就是老用户
        return user;
    }

    /**
     * 调用微信接口服务，获取微信用户的openid
     */
    private String getOpenId(UserLoginDTO userLoginDTO) {
        // 1.获取前端传入的授权码
        String code = userLoginDTO.getCode();
        // 2.对微信服务器发起请求，请求获取openId
        // 构建参数
        Map<String, String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        // 使用工具类调试
        String userInfoString = HttpClientUtil.doGet(WECHAT_URL, map);
        JSONObject jsonObject = JSON.parseObject(userInfoString);
        return jsonObject.getString("openid");
    }
}
